const { baserUrl } = require("./url.js").default;

const formatTime = (date) => {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hour = date.getHours();
    const minute = date.getMinutes();
    const second = date.getSeconds();

    return (
        [year, month, day].map(formatNumber).join("-") +
        " " + [hour, minute, second].map(formatNumber).join(":")
    );
};

const formatNumber = (n) => {
    n = n.toString();
    return n[1] ? n : "0" + n;f
};

/**
 * @Description: 获取今天的年月日
 * @Author: LiSuwan
 * @Return: {String} 今天的日期，格式“YYYY-MM-DD”
 * @Date: 2019-08-15 21:41:07
 */
let getToday = function() {
    let date = new Date();
    const year = date.getFullYear();
    let month = date.getMonth() + 1;
    if (month < 10) {
        month = "0" + month;
    }
    const day = date.getDate();
    return String(year) + "-" + month + "-" + day;
};

/**
 * @Description: 手机号码替换成星号
 * @Author: LiSuwan
 * @Param: {String} phone:手机号码
 * @Date: 2019-08-15 19:04:32
 */
let replaceTel = function(phone) {
    var showPhone = phone.replace(/^(\d{3})\d{4}(\d+)/, "$1****$2");
    return showPhone;
};

/**
 * @Description: 校验手机号码是否正确
 * @Author: LiSuwan
 * @Date: 2019-08-15 21:48:42
 */
let checkTelphone = function(phone) {
    return Boolean(regExp.telPhone.test(phone));
};
/**
 * @Description: 校验密码是否正确
 * @Author: chencheng
 * @Date: 2022-08-01 17:53:13
 * @param {*} password
 * @return {*}
 */
let checkPasswordLength = function(password) {
    return Boolean(regExp.passwordLength.test(password));
};
/**
 * @Description: 校验邮箱
 * @Author: Cheng Linmao
 * @Date: 2020-03-16 19:05:02
 */
let checkEmail = function(emial) {
    return Boolean(regExp.emial.test(emial));
};

// 校验身份证号合法性 start
var checkCode = function(val) {
    var p =
        /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    var parity = [1, 0, "X", 9, 8, 7, 6, 5, 4, 3, 2];
    var code = val.substring(17);
    if (p.test(val)) {
        var sum = 0;
        for (var i = 0; i < 17; i++) {
            sum += val[i] * factor[i];
        }
        if (parity[sum % 11] == code.toUpperCase()) {
            return true;
        }
    }
    return false;
};
var checkDate = function(val) {
    var pattern =
        /^(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)$/;
    if (pattern.test(val)) {
        var year = val.substring(0, 4);
        var month = val.substring(4, 6);
        var date = val.substring(6, 8);
        var date2 = new Date(year + "-" + month + "-" + date);
        if (date2 && date2.getMonth() == parseInt(month) - 1) {
            return true;
        }
    }
    return false;
};
var checkProv = function(val) {
    var pattern = /^[1-9][0-9]/;
    var provs = {
        11: "北京",
        12: "天津",
        13: "河北",
        14: "山西",
        15: "内蒙古",
        21: "辽宁",
        22: "吉林",
        23: "黑龙江 ",
        31: "上海",
        32: "江苏",
        33: "浙江",
        34: "安徽",
        35: "福建",
        36: "江西",
        37: "山东",
        41: "河南",
        42: "湖北 ",
        43: "湖南",
        44: "广东",
        45: "广西",
        46: "海南",
        50: "重庆",
        51: "四川",
        52: "贵州",
        53: "云南",
        54: "西藏 ",
        61: "陕西",
        62: "甘肃",
        63: "青海",
        64: "宁夏",
        65: "新疆",
        71: "台湾",
        81: "香港",
        82: "澳门",
    };
    if (pattern.test(val)) {
        if (provs[val]) {
            return true;
        }
    }
    return false;
};
/**
 * @Description: 校验身份证号合法性
 * @Author: LiSuwan
 * @Param:{String}:val:身份证号
 * @Date: 2019-12-25 21:01:20
 */
var checkID = function(val) {
    if (checkCode(val)) {
        var date = val.substring(6, 14);
        if (checkDate(date)) {
            if (checkProv(val.substring(0, 2))) {
                return true;
            }
        }
    }
    return false;
};
// 校验身份证号合法性 end

/**
 * @Description: 设置文章详情的图片尺寸
 * @Author: LiSuwan
 * @Param:{String}:content:文章详情的内容
 * @Date: @Date: 2019-11-20
 */
let setArticleDetailImgSize = function(content) {
    content = content.replace(
        /<img/g,
        '<img style="max-width:100%;height:auto" '
    );
    return content;
};

/**
 * @Description: 截取日期格式
 * @Author: Cheng Linmao
 * @Date: 2020-03-11 09:37:48
 * @param:{String}:time:处理的时间time,
 * 后台时间结构：time：2020-01-22 09:27:43;type:1,默认不截取;2,只截取日期;3,截取日期+时分;4、只截取时分秒
 * @return:
 */
let sliceTime = function(time, type = 1) {
    if (type == 1) {
        time = time.slice(0, 10) + " " + time.slice(11, 19);
    } else if (type == 2) {
        time = time.slice(5, 10);
    } else if (type == 3) {
        time = time.slice(5, 10) + " " + time.slice(11, 16);
    } else if (type == 4) {
        time = time.slice(11, 19);
    } else if (type == 5) {
        time = time.slice(0, 10);
    }
    return time;
};

/**
 * @Description: 身份证号码截取出生日期
 * @Author: Cheng Linmao
 * @Date: 2020-03-27 13:54:07
 * @param {type}  输入的身份证号码，老版15位，新版18位数
 * @return: birthday:返回的生日格式 1995-03-04   ("$1-$2-")可修改
 */
let getBirth = function(IDcard) {
    if (IDcard != null && IDcard != "") {
        if (IDcard.length == 15) {
            IDcard = "19" + IDcard.substr(6, 6);
        } else if (IDcard.length == 18) {
            IDcard = IDcard.substr(6, 8);
        }

        return (IDcard = IDcard.replace(/(.{4})(.{2})/, "$1-$2-"));
    }
};
/**
 * @Author      LiSuwan
 * @DateTime    2018-05-16
 * @description 格式化日期
 * @param       {Str}   date:日期
 * @param       {Str}   fmt:日期格式化方式
 * @return      {date}  fmt:返回格式化后的日期
 */
let formatDate = function(date, fmt) {
    var time = new Date(date);
    var o = {
        "M+": time.getMonth() + 1, //月份
        "D+": time.getDate(), //日
        "H+": time.getHours(), //小时
        "m+": time.getMinutes(), //分
        "s+": time.getSeconds(), //秒
        "q+": Math.floor((time.getMonth() + 3) / 3), //季度
        S: time.getMilliseconds(), //毫秒
    };

    if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(
            RegExp.$1,
            String(time.getFullYear()).substr(4 - RegExp.$1.length)
        );
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(String(o[k]).length)
            );
        }
    }

    return fmt;
};

/**
 * @Description: 获取上传的文件名后缀名、文件名称
 * @Author: LiSuwan
 * @Date: 2020-01-07 10:01:56
 * @param {Object} fileData:上传的文件对象
 * @return: {String} type:文件名称
 */
var getUploadFileName = function(fileData) {
    let file = fileData.files[0]; //获取上传的文件
    let fileName = file && file.name; //上传的文件名
    var point = fileName.lastIndexOf(".");
    var type = fileName.substr(point + 1);
    return { type, fileName };
};

/**
 * @Description: 获取指定月份中的天数
 * @Author: XiaoFangjun
 * @Date: 2021-10-14 15:02:59
 * @param {Object} fileData:上传的文件对象
 * @return: {String} type:文件名称
 */
function getMonthDays(year, month) {
    var thisDate = new Date(year, month, 0); //当天数为0 js自动处理为上一月的最后一天
    return thisDate.getDate();
}

/**
 * @Description: 批量下载
 * @Author: XiaoFangjun
 * @Date: 2021-10-19 13:54:16
 * @param {String} url:需要下载的文件路径
 */
export const downloadFile = (url) => {
    const iframe = document.createElement("iframe");
    iframe.style.display = "none"; // 防止影响页面
    iframe.style.height = 0; // 防止影响页面
    iframe.src = url;
    document.body.appendChild(iframe); // 这一行必须，iframe挂在到dom树上才会发请求
    // 5分钟之后删除
    // setTimeout(() => {
    //   iframe.remove()
    // }, 5 * 60 * 1000)
};

// function saveAs(data, name) {
//   const urlObject = window.URL || window.webkitURL || window;
//   const export_blob = new Blob([data]);
//   const save_link = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
//   save_link.href = urlObject.createObjectURL(export_blob);
//   save_link.download = name;
//   save_link.click();
//   let formData3 = new FormData()
//   formData3.append('taskid', id);
//   postAction(_that.downloadOver, formData3)
// }

/**
 * @Description: 下载文件
 *               下载的文件域名需和当前页面域名一致才会触发下载 否则是新开浏览器tab页预览
 * @Author: ZhaoYingxin
 * @Date: 2022-06-28 13:52:08
 * @param {string} url
 * @param {string} fileName
 */
function downloadFileX(url, fileName = "") {
    let a = document.createElement("a");
    var fileType = url.substr(url.lastIndexOf(".") + 1).toLowerCase();
    var download = fileName + "." + fileType;
    a.setAttribute("href", url);
    a.setAttribute("download", download);
    a.setAttribute("target", "_blank");
    a.click();
    // a标签未插入文档中 所以无需销毁
}
/**
 * @Description: 保留小数点后两位
 * @Author: XiaoFangjun
 * @Date: 2021-10-21 9:42:16
 * @param {String} url:需要下载的文件路径
 */
function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
        return false;
    }
    f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf(".");
    if (rs < 0) {
        rs = s.length;
        s += ".";
    }
    while (s.length <= rs + 2) {
        s += "0";
    }
    return s;
}
/**
 * @Description: 销毁当前页面面包屑的tab
 * @Author: LiSuwan
 * @Date: 2022-08-24 11:25:34
 * @param {*} that:当前页面实例
 *
 */
function destoryTab(that) {
    const _curPath = that.$route.path.replace("/layout/", "");
    that.$store.commit("header/autoDelHeaderNavData_editPage", _curPath);
}
/**
 * @Description: form方式下载文件
 * @Author: ZhaoYingxin
 * @Date: 2022-08-26 11:42:53
 * @param {string} url
 * @param {请求参数} params
 * @return {*}
 */
function downloadFileByForm(url, params) {
    var form = document.createElement("form");
    form.id = "downloadFileForm";
    form.name = "downloadFileForm";
    document.body.appendChild(form);

    for (const obj in params) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = obj;
        input.value = params[obj];
        form.appendChild(input);
    }

    form.method = "post"; //请求方式
    form.action = url;
    form.submit();
    document.body.removeChild(form); //移除form表单标签
}

/**
 * @Description: 小数点之后自动补0
 * @Author: LiSuwan
 * @Date: 2020-09-30 15:01:57
 * @param {type}
 * @return {type}
 */
var returnFloat = function(value) {
    var value = Math.round(parseFloat(value) * 10) / 10;
    var xsd = value.toString().split(".");
    if (xsd.length == 1) {
        value = value.toString() + ".0";
        return value;
    }
    if (xsd.length > 1) {
        if (xsd[1].length < 2) {
            value = value.toString() + "";
        }
        return value;
    }
};

/**
 * @Description: 日期比较大小
 * compareDateString大于dateString，返回1；
 * 等于返回0；
 * compareDateString小于dateString，返回-1
 * @Author: Cheng Linmao
 * @Date: 2020-09-26 09:22:27
 * @param dateString 日期
 * @param compareDateString 比较的日期
 * @param type 类型：1riqi 2：时间戳
 * @return {type}
 */

var dateCompare = function(dateString, compareDateString, type = 1) {
    if (type == 2) {
        var dateTime = dateString;
        var compareDateTime = compareDateString;
    } else {
        var dateTime = dateParse(dateString);
        var compareDateTime = dateParse(compareDateString);
    }
    if (compareDateTime > dateTime) {
        return 1;
    } else if (compareDateTime == dateTime) {
        return 0;
    } else {
        return -1;
    }
};

/**
 * @Description: 日期解析，字符串转日期
 * @Author: Cheng Linmao
 * @Date: 2020-09-26 09:23:23
 * @param {type} dateString 可以为2017-02-16，2017/02/16，2017.02.16
 * @return {Date} 返回对应的日期对象
 */
function dateParse(dateString) {
    return new Date(dateString.replace(/-/g, "/")).getTime();
}
/**
 * @Description: 时间戳转年月日  参数是秒的时间戳
 * @Author: LvHaoNan
 * @Date: 2023-02-03 13:31:23
 * @param {*} long
 * @return {*} 返回一个对象 对象里有年 月 日
 */
function yearDay(long) {
    var time = new Date(long * 1000);
    var year = time.getFullYear();
    var month =
        time.getMonth() + 1 < 10 ?
        "0" + (time.getMonth() + 1) :
        time.getMonth() + 1;
    var date = time.getDate() < 10 ? "0" + time.getDate() : time.getDate();
    var yearday = { year, month, date };
    return yearday;
}

/**
 * @Description: 获取今年有多少周
 * @Author: LvHaoNan
 * @Date: 2023-02-03 13:32:29
 * @param {*} year
 * @return {*}返回一个数组，数组里的对象包含 这一周的开始日期和结束日期
 */
//计算一年中的每一周都是从几号到几号
//第一周为1月1日到 本年的 第一个周日
//第二周为 本年的 第一个周一 往后推到周日
//以此类推 再往后推52周。。。
//如果最后一周在12月31日之前，则本年有垮了54周，反之53周
//12月31 日不论是周几，都算为本周的最后一天
//参数年份 ，函数返回一个数组，数组里的对象包含 这一周的开始日期和结束日期
function whichWeek(year) {
    var d = new Date(year, 0, 1);
    while (d.getDay() != 1) {
        d.setDate(d.getDate() + 1);
    }
    let arr = [];
    let longnum = d.setDate(d.getDate());
    if (longnum > +new Date(year, 0, 1)) {
        let obj = yearDay(+new Date(year, 0, 1) / 1000);
        obj.last = yearDay(longnum / 1000 - 86400);
        arr.push(obj);
    }
    let oneitem = yearDay(longnum / 1000);
    oneitem.last = yearDay(longnum / 1000 + 86400 * 6);
    arr.push(oneitem);
    var lastStr;
    for (var i = 0; i < 51; i++) {
        let long = d.setDate(d.getDate() + 7);
        let obj = yearDay(long / 1000);
        obj.last = yearDay(long / 1000 + 86400 * 6);
        lastStr = long + 86400000 * 6;
        arr.push(obj);
    }
    if (lastStr < +new Date(year + 1, 0, 1)) {
        let obj = yearDay(lastStr / 1000 + 86400);
        obj.last = yearDay(+new Date(year + 1, 0, 1) / 1000 - 86400);
        arr.push(obj);
    } else {
        arr[arr.length - 1].last = yearDay(+new Date(year + 1, 0, 1) / 1000 - 86400);
    }
    return arr;
}

/**
 * @Description: 判断是否登录
 * @Author: LiSuwan
 * @Date: 2023-02-13 20:22:56
 * @param {*} showModal:false 显示showModal，默认可以不传这个值
 */
function isLogin(showModal, code) {
    let userInfo = uni.getStorageSync("userInfo");

    if ((!userInfo && !showModal) || code == 401) {
        return uni.showModal({
            title: "提示",
            content: "暂未登录，请先登录",
            showCancel: true, //是否显示取消按钮，默认为 true
            success: function(res) {
                if (res.confirm) {
                    uni.clearStorage();
                    uni.reLaunch({
                        url: "/pages/login/login",
                    });
                }
            },
        });
    }

    if (!userInfo && showModal) {
        return false;
    }

    return true;
}

/**
 * @Description: 处理课时状态
 * @Author: LiSuwan
 * @Date: 2023-02-17 16:59:59
 */
function handerClassHourStatus(str) {
    let classIsOver = -1;
    switch (
        str //1:待开始 2：进行中3：已结束
    ) {
        case "待开始":
            classIsOver = 1;
            break;
        case "进行中":
            classIsOver = 2;
            break;
        case "已结束":
            classIsOver = 3;
            break;
    }
    return classIsOver;
}

/**
 * @Description:  校验积分范围0-10
 * @Author: LiSuwan
 * @Date: 2023-02-20 18:50:06
 * @param {*} value:积分
 */
function checkScoreRange(value) {
    // 判断得分输入是否为空或者0-10
    if (value.length > 1 && value.slice(0, 1) == 0) {
        uni.showToast({
            icon: "none",
            title: "请输入(0-10分)",
        });
        return false;
    }
    if (
        (value != "" && Number(value) > 10) ||
        (value != "" && String(value).indexOf(".") > -1)
    ) {
        uni.showToast({
            icon: "none",
            title: "请输入(0-10分)",
        });
        return false;
    }
    return true;
}
/**
 * @Description: 把对象转化URL参数
 * @Author: LiSuwan
 * @Date: 2023-02-21 11:43:37
 */
function objTransformUrlParams(obj) {
    let urlParams = "";
    for (var key in obj) {
        if (urlParams.length == 0) {
            urlParams += key + "=" + obj[key];
        } else {
            urlParams += "&" + key + "=" + obj[key];
        }
    }
    return urlParams;
}

/**
 * @Description: 处理字段默认值
 * @Author: LiSuwan
 * @Date: 2023-03-01 11:48:26
 * @param {*} value:处理的字段
 * @param {*} otherValue：给予的值
 */
function handleFieldValue(value, otherValue) {
    let defaultValue = "/"; //默认值
    if (value == null || value == "null" || value == 0) {
        //他评
        defaultValue = "/";
    } else {
        defaultValue = value;
    }

    if (otherValue) {
        defaultValue = otherValue;
    }

    return defaultValue;
}



/**
 * @Description: 设置富文本图片的公共路径，实际使用的时候需要修改下方法
 * @Author: LiSuwan
 * @Param:{String}:content:文章详情的内容
 * @Date: @Date: 2019-11-20
 */
let setArticleDetailImgSrc = function(content) {
    content = content.replace(
        /"\/projectimg\/\/ueditor/g,
        '"' + baserUrl + "projectimg/ueditor"
    );
    return content;
};


/**
 * @Description: 是否有下一页
 * @Author: LiSuwan
 * @Date: 2023-09-23 11:53:29
 * @param {*} total:总条数
 * @param {*} page:页码
 * @param {*} currentPageNum：当前页面的数据条数
 * @param {*} pageSize：每页显示的条数 默认是：10
 */
let hasNextPage = function(total, page, currentPageNum, pageSize = 10) {
    let hasNextPage = false; //是否有下一页 false:无 true:有
	
    if (page == 1 && (total > currentPageNum)) { //page = 1,当前页面的条数 <= total，表示没有下一页
        hasNextPage = true;
    } else if (total > ((page - 1) * pageSize + currentPageNum)) { //之前的页面条数+加上当前页面的条数<= total,表示没有下一页
        hasNextPage = true;
    }
    return hasNextPage;

};


/**
 * @Description: 校验只能输入数字
 * @Author: LiSuwan
 * @Date: 2023-09-25 19:30:05
 * @param {*} value
 * @return {*}
 */
function check_validateNumber(value) {
    var reg = /^\d+$/; // 定义正则表达式
    if (value.constructor === String) { // 判断传入的是否是字符串   
        var reg = value.match(reg); // 规则校验
        return true;
    }

    return false;

}

/**
 * @Description: 清除新增订单用到的缓存变量的值
 * @Author: LiSuwan
 * @Date: 2023-10-04 12:07:53
 */
function removeStorageSyncByOrder() {
    uni.removeStorageSync('selectedSpecialProject'); //清除缓存中获取选择的特殊类项目
    uni.removeStorageSync('applicationOne'); //清除缓存中报名第一步数据
    uni.removeStorageSync('applicationTwo'); //清除缓存中报名第二步数据
    uni.removeStorageSync('applicationThree'); //清除缓存中报名第三步数据
    uni.removeStorageSync("selectCompany"); //清除缓存中的特殊类项目
    uni.removeStorageSync("regulationList"); //清除缓存中的特殊类项目
    uni.removeStorageSync("applyTrainProject"); //清除缓存中的申请培训项目数据
    uni.removeStorageSync("selectProjectList"); //清除缓存中的选择的申请项目



}
const locationByAPP = () => {
	console.log(111)
    return new Promise((resolve, reject) => {
		
        uni.getLocation({
            type: 'wgs84', // 返回可以用于uni.openLocation的经纬度，默认为wgs84的gps坐标
			geocode:true,
            success: function (res) {
              
				resolve(res)
            },
            fail: function (error) {
            },
			complete:function(res){
				console.log(res,"完成")
			}
        });
    });
};






const getDeviceInfo = ()=>{
	return uni.getSystemInfoSync()
}



const pageTop = ()=>{
	let { statusBarHeight } = getDeviceInfo()
	let navigationBarHeight = statusBarHeight  + 'rpx';
	return 120 + 'rpx'; 
	
}
			
			

//compareTime接受两个时间字符串作为参数，并返回一个表示它们相对顺序的值：-1 表示第一个时间早于第二个时间，0 表示两者相等，1 表示第一个时间晚于第二个时间。
const compareTime =  (time1, time2) =>{
  // 将时间转换为秒
  function timeToSeconds(time) {
    var parts = time.split(':');
    return parts[0] * 3600 + parts[1] * 60;
  }
 
  // 转换并比较
  var seconds1 = timeToSeconds(time1);
  var seconds2 = timeToSeconds(time2);
  if (seconds1 < seconds2) {
    return -1; // time1 小于 time2
  } else if (seconds1 > seconds2) {
    return 1; // time1 大于 time2
  } else {
    return 0; // time1 等于 time2
  }
}

export default {
	pageTop,
	compareTime,
	locationByAPP,
	getDeviceInfo,
    removeStorageSyncByOrder,
    check_validateNumber,
    hasNextPage,
    formatTime: formatTime,
    getToday: getToday,
    replaceTel: replaceTel,
    checkTelphone: checkTelphone,
    checkPasswordLength: checkPasswordLength,
    setArticleDetailImgSize: setArticleDetailImgSize,
    sliceTime: sliceTime,
    checkEmail: checkEmail,
    checkID: checkID,
    getBirth: getBirth,
    formatDate: formatDate,
    getUploadFileName: getUploadFileName,
    getMonthDays,
    downloadFile,
    toDecimal2,
    downloadFileX,
    destoryTab,
    downloadFileByForm,
    returnFloat,
    dateCompare,
    dateParse,
    whichWeek,
    isLogin,
    handerClassHourStatus,
    checkScoreRange,
    objTransformUrlParams,
    handleFieldValue,
    setArticleDetailImgSrc,
};